package com.ccsu.mymarket.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccsu.mymarket.controller.utils.DataUtils;
import com.ccsu.mymarket.dao.ShopDao;
import com.ccsu.mymarket.dao.UserDao;
import com.ccsu.mymarket.entity.Shop;
import com.ccsu.mymarket.entity.User;
import com.ccsu.mymarket.exception.MyException;
import com.ccsu.mymarket.service.AuthorityService;
import com.ccsu.mymarket.service.RoleService;
import com.ccsu.mymarket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    private final UserDao userDao;
    private final ShopDao shopDao;
    private final RoleService roleService;
    private final AuthorityService authorityService;

    public UserServiceImpl(@Autowired UserDao userDao, @Autowired ShopDao shopDao, @Autowired RoleService roleService, @Autowired AuthorityService authorityService) {
        this.userDao = userDao;
        this.shopDao = shopDao;
        this.roleService = roleService;
        this.authorityService = authorityService;
    }

    /**
     * 根据用户名和角色查询所有用户
     * 登录时用
     *
     * @param user
     * @return 用户列表
     */
    private List<User> getUsersByNameRole(User user) throws MyException {
        if (user.getRole() == null)
            throw new MyException("角色id为空，无法登录！");

//        根据前端传入的 角色id 和 用户名 查找用户列表
        List<User> userList = userDao.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getRole, user.getRole())
                .eq(User::getAccName, user.getAccName()));

        switch (user.getRole()) {
//            前端商城允许 商家 或者 买家 登录
//            所以除了买家外，还要查询商家
            case 1: {
                List<User> buyerList = userList;
                List<User> sellerList = userDao.selectList(new LambdaQueryWrapper<User>()
                        .eq(User::getRole, 2)
                        .eq(User::getAccName, user.getAccName()));
                buyerList.addAll(sellerList);
                return buyerList;
            }
            default: {
                return userList;
            }
        }
    }

    @Override
    public User checkLoginInfo(User user) throws MyException {
//        用户角色 + 用户名检查
        List<User> userList = getUsersByNameRole(user);
        if (userList == null) {
            throw new MyException("用户名错误！");
        }
//        用户id -> 用户密码检查
        List<Integer> idList = new ArrayList<>();
        for (User user1 : userList) {
            idList.add(user1.getId());
        }
        User sccucessUser = userDao.selectOne(new LambdaQueryWrapper<User>()
                .in(User::getId, idList).eq(User::getPass, user.getPass()));
        if (sccucessUser == null) {
            throw new MyException("密码错误！");
        }
//        校验信息通过，查询视图，获得信息返回前端
        User userInfo = userDao.getUserById(sccucessUser.getId());
        if (userInfo==null)
            throw new MyException("该用户正在审核中，无法登录！");
        return userInfo;
    }

    @Override
    @Transactional
    public boolean registerIn(Map data) throws MyException {
        Integer role= (Integer) data.get("role");
        switch (role){
//            普通用户
            case 1:{
                try {
                    User user= DataUtils.mapToBean(data,User.class);
                    user.setRegisterTime(DataUtils.getDateTime(2));
                    return userDao.insert(user)>0;
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new MyException("普通用户注册失败，请检查数据格式是否正确！");
                }
            }
//            商家
            case 2:{
                try {
                    // 提取店铺信息
                    String shopName= (String) data.remove("shopName");
                    Integer type= (Integer) data.remove("type");
                    Integer registerMoney= (Integer) data.remove("registerMoney");
                    // 提取用户信息
                    User user= DataUtils.mapToBean(data,User.class);
                    user.setRegisterTime(DataUtils.getDateTime(2));
                    //存入用户信息
                    userDao.insert(user);
                    Integer userId=userDao.selectOne(new LambdaQueryWrapper<User>()
                            .eq(User::getAccName,user.getAccName())
                            .select(User::getId)).getId();

                    //创建店铺对象
                    Shop shop=new Shop();
                    shop.setAcc(userId);
                    shop.setShopName(shopName);
                    shop.setType(type);
                    shop.setRegisterMoney(registerMoney);

                    //存入店铺信息
                    shopDao.insert(shop);

                } catch (Exception e) {
                    e.printStackTrace();
                    throw new MyException("商家注册失败，请检查数据格式是否正确！");
                }
            }
        }
        return true;
    }


    @Override
    public List<Integer> getShopBookIds(Integer sellerId) {
        return userDao.getShopBookIds(sellerId);
    }

    @Override
    public boolean updateSellerInfo(Integer shopId, Integer shopType, String phone) {
//        店铺id -> 店铺对象 -> 用户id -> 修改用户信息或商店信息
        Shop shop = shopDao.selectOne(new LambdaQueryWrapper<Shop>()
                .eq(Shop::getId, shopId).select(Shop::getAcc));
        Integer userId = shop.getAcc();

        shopDao.update(shop, new LambdaUpdateWrapper<Shop>()
                .eq(Shop::getId, shopId)
                .set(shopType != null, Shop::getType, shopType));

        userDao.update(new User(), new LambdaUpdateWrapper<User>()
                .eq(User::getId, userId)
                .set(phone != null, User::getPhone, phone));
        return true;
    }

    @Override
    public boolean checkAcount(Integer id) throws MyException {
        if (userDao.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, id)
                .eq(User::getState, 0))
                != null)
            return true;
        else {
            throw new MyException("该用户不存在！");
        }
    }

    @Override
    public boolean updateUserInfo(User user) {
        int row=userDao.update(user, new LambdaUpdateWrapper<User>()
                        .eq(User::getId, user.getId())
                        .set(user.getSex() != null && user.getSex() != "", User::getSex, user.getSex())
                        .set(User::getAddressDefault, user.getAddressDefault())
        );
        if (row>0)
            return true;
        return false;
    }

    @Override
    public boolean updateUserByAdmin(User user) {
        int row=userDao.update(user,new LambdaUpdateWrapper<User>()
                .eq(User::getId,user.getId())
                //          修改用户密码
                .set(user.getPass() != null && user.getPass() != "", User::getPass, user.getPass())
                .set(user.getPhone() != null, User::getPhone, user.getPhone())
                .set(user.getState() != null, User::getState, user.getState()));
        if (row>0)
            return true;
        return false;
    }

}
